import csv
import states
import requests

from bs4 import BeautifulSoup


def request(method, params):
	params['key'] = 'x'
	r = requests.get('http://api.votesmart.org/' + method, params=params)
	#print r.url
	return BeautifulSoup(r.text, 'xml')


### VOTES
def getVotes(vote_id):
	votes = []
	soup = request('Votes.getBillActionVotes', {'actionId': vote_id})
	for vote in soup.find_all('vote'):
		votes.append({'vote_id': vote_id, 'candidateId': vote.candidateId.text, 'action': vote.action.text})
	return votes


vote_ids = []
with open('vote_and_group_info_map.csv', 'rbU') as csvfile:
	r = csv.DictReader(csvfile, delimiter=',')
	for row in r:
		vote_ids.append(row['house_vote_id'])


with open('votes.csv', 'w') as csv_file:
	writer = csv.DictWriter(csv_file, ['vote_id', 'candidateId', 'action'], extrasaction='ignore')
	writer.writeheader()
	for vote_id in vote_ids:
		print 'Now on vote id %s' % vote_id
		for vote in getVotes(vote_id):
			try:
				writer.writerow(vote)
			except:
				print 'Failed on vote %s' % vote